<template>
  <el-select
    ref="select"
    :multiple="isMultiple"
    v-model="selectedValue"
    filterable
    remote
    clearable
    :remote-method="remoteMethod"
    :loading="loading"
    @change="onChange"
    :disabled="disabled"
  >
    <el-option
      :disabled="option.isBind"
      v-for="option in options"
      :label="option.label"
      :key="option.value"
      :value="option.value"
      >{{ option.label }}</el-option
    >
  </el-select>
</template>
<script>
import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
export default {
  props: {
    // disabled: Boolean,       
    url: String,
    queryParamers: {
      type: Object,
      default: () => {},
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
    queryName: String,
    businessId: Number,
  },
  data() {
    return {
      selectedValue: "",
      loading: false,
      options: [],
      disabled: false,
      selectedOptions: [],
    };
  },
  watch: {
    queryName(val, oldval) {
      this.$nextTick(() => {
        this.selectedValue = val;
        this.$forceUpdate();
      });
    },
  },
  mounted() {
    // console.log(this.queryName);
  },
  methods: {
    changeName(val) {
      this.setQuery(val);
    },
    clear() {
      // this.$refs['select'].clearSingleSelect()
      this.selectedValue = "";
    },
    setQuery(val) {
      this.$refs["select"].setQuery(val);
    },
    remoteMethod(query) {
      if (query === "") {
        this.options = [];
        return;
      }
      this.loading = true;
      const data = {
        keyword: query,
        businessId: this.businessId,
      };
      for (let key in this.queryParamers) {
        data[key] = this.queryParamers[key];
      }
      axios
        .request({
          url: process.env.VUE_APP_BASE_API + this.url,
          params: data,
          method: "get",
          headers: {
            marketId: store.state.app.marketId,
            Authorization: getToken(),
          },
        })
        .then((res) => {
          let data = res.data.data;
          // console.log(data);
          let items = [];
          for (let item of data) {
            let isBind = false;
            if ("isBind" in item) {
              isBind = item.isBind;
            }
            items.push({
              value: item.supplier_source_id + "",
              label: item.supplier_name,
              supplier_source_type: item.supplier_source_type,
              stallName: item.stallName,
              businessOpenId: item.businessOpenId,
              exData: item,
              isBind: isBind,
            });
          }
          // console.log(items);
          this.options = items;
          this.loading = false;
          // console.log(this.options);
          // console.log(this.options)
          // console.log("query"+ query)
          // for (let i = 0; i < this.options.length; i++) {
          //   if (this.options[i].lable === query) {
          //     this.$emit('selected', this.options[i])
          //     break
          //   }
          // }
        })
        .catch((_) => {
          this.loading = false;
          this.options = [];
          this.options.push({
            label: query,
            value: "999999999",
            supplier_source_type: "3",
            stallName: "",
            isBind: false,
            businessOpenId: "",
            exData: { id: "999999999", name: query },
          });
        });
    },
    onChange(it) {
      if (this.isMultiple === true) {
        let newselectedValue = it.map((item) => ({ value: item }));

        let selectedOption = null;
        let finded = false;
        for (let ai of newselectedValue) {
          if (finded) {
            break;
          }
          for (let bi of this.options) {
            if (ai.value === bi.value) {
              selectedOption = bi;
              finded = false;
              break;
            }
          }
        }
        if (selectedOption != null) {
          let contan = false;
          for (let i of this.selectedOptions) {
            if (i.value == selectedOption.value) {
              contan = true;
            }
          }

          if (!contan) {
            this.selectedOptions.unshift(selectedOption);
          }
        }

        // 移除
        let notDeleted = [];
        for (let si of this.selectedOptions) {
          for (let v of it) {
            if (v == si.value) {
              notDeleted.unshift(si);
            }
          }
        }

        this.selectedOptions = notDeleted;

        console.log("selectedOptions", this.selectedOptions);

        // this.$emit('selected', this.selectedOptions)
        this.$emit("selected", it);
        console.log("over");
      } else {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].value === this.selectedValue) {
            this.$emit("selected", this.options[i]);
            break;
          }
        }
      }
    },
  },
};
</script>
